# frozen_string_literal: true

require 'spec_helper'

RSpec.shared_examples 'vulnerability and finding shared examples' do
  describe 'scopes' do
    let(:result_set_transformer) { transformer_method || :itself }
    let(:archive_associated_objects) { archived_project.vulnerabilities.map(&result_set_transformer) }
    let(:all_excluding_archive_associations) { all_vulns_for_params - archive_associated_objects }

    let_it_be(:vulnerability) { create(:vulnerability, :with_finding, project: project) }
    let_it_be(:archived_project) do
      create(:project, :archived).tap { |p| create(:vulnerability, :with_finding, project: p) }
    end

    describe '.without_archived_projects' do
      subject { described_class.without_archived_projects }

      let(:all_vulns_for_params) { described_class.all }

      it 'returns objects where the associated project is not archived' do
        is_expected.to contain_exactly(*all_excluding_archive_associations)
      end
    end

    describe '.for_projects' do
      subject { described_class.for_projects(*params) }

      let(:include_archived) { nil }

      let(:params) { [[project.id, archived_project.id], include_archived].compact }
      let(:all_vulns_for_params) do
        (project.vulnerabilities + archived_project.vulnerabilities).map(&result_set_transformer)
      end

      before do
        # vulnerability associated on a project that will be filtered out
        create(:vulnerability, :with_finding, project: create(:project))
      end

      it 'returns objects related to the given project IDs' do
        is_expected.to contain_exactly(*all_excluding_archive_associations)
      end

      context 'when including archived projects' do
        let(:include_archived) { true }

        it 'returns objects related to the given project IDs' do
          is_expected.to contain_exactly(*all_vulns_for_params)
        end
      end

      context 'when excluding archived projects' do
        let(:include_archived) { false }

        it 'returns objects related to the given project IDs' do
          is_expected.to contain_exactly(*all_excluding_archive_associations)
        end
      end
    end
  end
end
